<template>
  <span class="imitationinput" ref="imitationinput" >
    <slot></slot>
  </span>
</template>

<script>
import Bus from "@/assets/js/bus.js";
import { getoffsettop } from "@/assets/js/Getoffsettop.js";

export default {
  name: "imitationinput",
  data() {
    return {
      content: "",
      nowcontent:"",
      timer:null,
    };
  },
  props:{
   
  },
  mounted() {
    this.content = this.$refs.imitationinput.innerText.split("");  
    this.imitationinput();
    Bus.$on("isscroll", (data) => {
      if (
        data.scrolltop + data.clientheight >
          getoffsettop(this.$refs.imitationinput) &&
        data.scrolltop + data.clientheight <
          data.clientheight + getoffsettop(this.$refs.imitationinput)
      ) {
        this.imitationinput();
      }
    });
  },
  beforeDestroy() {
    Bus.$off("isscroll");
    this.$refs.imitationinput.innerText=this.content.join("")
    this.timer=null;
  },
  methods: {
    imitationinput() {
      if(!this.timer){
        this.$refs.imitationinput.innerText = "";
        this.nowcontent = [];
        for (let x in this.content) {
          //利用函数自身的作用域，在定时器外部嵌套一个匿名函数，将for循环的x作为参数传递给匿名函数，使得延迟函数的回调可以将新的作用域封闭在每次迭代的内部。
          ((time) => {
            this.timer=setTimeout(() => {
              this.nowcontent.push(this.content[x]);
              this.$refs.imitationinput.innerText = this.nowcontent.join("");
              if(time==this.content.length-1){
                 this.timer=null;
              }
            }, 100 * time);
          })(x);
        }
      }
    },
  },
};
</script>

<style scoped>

.imitationinput {
  position: relative;
}
.imitationinput::before {
  position: absolute;
  right: -0.6em;
  bottom: 0rem;
  display: block;
  height: 100%;
  font-size: 1em;
  line-height: 1em;
  content: "▊";
  animation: inputmove 1s infinite;
}
@keyframes inputmove {
  100% {
    opacity: 0;
  }
}
</style>